from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import View, APIView
from rest_framework import status
from rest_framework.generics import GenericAPIView
from .utils import OAuthQQ
from .models import OAuthQQUser
import logging
from rest_framework_jwt.settings import api_settings
from .exceotions import QQAPIException
from . import serializers
from  carts.utils import merge_cart_cookie_to_redis
from carts.utils import merge_cart_cookie_to_redis
from rest_framework_jwt.views import ObtainJSONWebToken
logger = logging.getLogger('django')
# Create your views here.




# GET /oauth/qq/user/?code=xxx
class QQAuthUserView(GenericAPIView):
    """
    处理oauth_callback回调页面时
    提取code,access_token,openid
    """
    serializer_class = serializers.QQAuthUserSerializer
    def get(self,request):
        """提取code请求参数"""
        #获取code请求参数
        code = request.query_params.get('code')
        #判断是否存在
        if code is None:
            return Response({'message':'参数缺失'},status=status.HTTP_400_BAD_REQUEST)
        #创建OAuthQQ对象
        oauth = OAuthQQ()
        try:
            #使用code向qq服务器请求access_token
            access_token = oauth.get_access_token(code)
            #使用access_token向qq服务器请求openid
            open_id = oauth.get_open_id(access_token)
        except QQAPIException as e:
            logging.error(e)
            return Response({'message':'QQ服务异常'},status=status.HTTP_503_SERVICE_UNAVAILABLE)
        #使用openid查询该qq用户是否在梅朵商城绑定过
        try:
            # OAuthQQUser.objects.get(openid=open_id)
            #oauth_model:代表一条记录，OAuthQQUser类型的对象
            oauth_model = OAuthQQUser.objects.get(openid = open_id)
        except OAuthQQUser.DoesNotExist:
            #如果没有就说明没有绑定过 ,创建用户并且绑定openid
            token_openid = oauth.generate_save_user_token(open_id)
            #将openid签名后的结果响应给用户
            return Response({'access_token':token_openid})




        else:
            #绑定过直接生成JWT——token登录
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

          # 获取跟openid绑定的user对象
            user = oauth_model.user
            payload = jwt_payload_handler(user)
            #JWT token
            token = jwt_encode_handler(payload)

            #响应数据
            response=Response({
                'token':token,
                'user_id':user.id,
                'user_name':user.username
            })
            #合并cookie中的购物车数据到reids
            response = merge_cart_cookie_to_redis(request=request, user=user, response=response)
            return response
    def post(self, request):
        """openid绑定用户"""
        # 创建序列化器
        serializer = self.get_serializer(data=request.data)
        # 校验
        serializer.is_valid(raise_exception=True)
        # 调用create方法，实现绑定用户的保存
        user = serializer.save()

        # 生成状态保持信息
        # 生成JWT token，并响应
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        # 合并cookie中的购物车数据到redis
        response= Response({
            'token': token,
            'username': user.username,
            'user_id': user.id
        })

        response = merge_cart_cookie_to_redis(request=request, user=user, response=response)

        return response

#  url(r'^qq/authorization/$', views.QQAuthURLView.as_view()),
class QQAuthURLView(APIView):
    """qq登录后端接口设计"""
    def get(self,request):
        #获取next参数
        next = request.query_params.get('next')
        #创建OAuthQQ对象
        oauth = OAuthQQ(state=next)
        #获取qq扫码登录页面的网址
        login_url = oauth.get_login_url()

        #返回json数据 返回值login_url
        return Response({'login_url':login_url})

